package com.gdzl_hadoop.controller;

import com.gdzl_hadoop.common.Const;
import com.gdzl_hadoop.common.ResponseCode;
import com.gdzl_hadoop.common.ServerResponse;
import com.gdzl_hadoop.pojo.User;
import com.gdzl_hadoop.service.IUserService;
import com.gdzl_hadoop.util.HttpClientUtil;
import com.gdzl_hadoop.util.PropertiesUtil;
import com.gdzl_hadoop.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 1032019725 on 2017/10/17.
 */

@Controller
@RequestMapping("user")
public class UserController {

    //    private static final String URL = "http://39.108.213.149:8080/backstage/openInterface/login";
    @Autowired
    private IUserService iUserService;

    @ResponseBody
    @RequestMapping(value = "login.do")
    public ServerResponse login(HttpSession session, @RequestBody String email, @RequestBody String password) throws Exception {
        //从前端接受的账户与密码
        //   String account = "969@qq.com";
        //    String password = "123456";

        String url = PropertiesUtil.getProperty("loginUrl");
        String roleUrl = PropertiesUtil.getProperty("roleUrl");
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        //进行登录
        if (httpClientUtil.doLogin(url, email, password)) {
            //获取登录的token
            System.out.println("token: " + httpClientUtil.getToken());
            //获取个人信息
            System.out.println("个人信息:" + httpClientUtil.getUser());
            //获取角色信息
            ArrayList arrayList = httpClientUtil.getRoles(roleUrl, httpClientUtil.getToken());
            //          System.out.println(arrayList);
            for (Object e : arrayList) {
                HashMap hashMap = (HashMap) e;
                System.out.println(hashMap.get("roleRemark"));
                Map map = new HashMap<String, String>();
                if (hashMap.get("roleRemark").equals("专家用户")) {//专家用户
                    session.setAttribute("role", 1);
                    map.put("role", 1);
                    return ServerResponse.createBySuccess("登录成功", map);
                } else {//业务用户
                    session.setAttribute("role", 0);
                    session.setAttribute("xzqdm", hashMap.get("roleRemark"));

                    map.put("role", 0);
                    map.put("xzqdm", hashMap.get("roleRemark"));
                    return ServerResponse.createBySuccess("登录成功", map);
                }
            }
        }

        return ServerResponse.createByErrorMessage(httpClientUtil.getMsg());
    }

    @RequestMapping("loginResult.do")
    @ResponseBody
    public ResultUtil returnLoginIfo(HttpServletRequest req, @ModelAttribute("result") ResultUtil result) {
        req.getSession().setAttribute("result", result);

        return result;
    }
    /*
     *//**
     * 用户登录
     * @param username
     * @param userpwd
     * @param session
     * @return
     *//*
    @RequestMapping(value = "login.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> login(String username, String userpwd, HttpSession session)
    {
        //调用流程controller-->service-->dao
        ServerResponse<User> response = iUserService.login(username,userpwd);
        if(response.isSuccess()){
            session.setAttribute(Const.CURRENT_USER,response.getData());
        }
        return response;
    }*/

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "logout.do")
    @ResponseBody
    public ServerResponse<String> logout(HttpSession session) {
        session.removeAttribute("role");
        session.invalidate();
        return ServerResponse.createBySuccess();
    }

    /**
     * 注册
     *
     * @param user
     * @return
     *//*
    @RequestMapping(value = "register.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(User user) {

        //  int a = 1;
        return iUserService.register(user);
    }*/

    /**
     * 验证是否在数据库中存在type类型的，值为str的数据
     *
     * @param str
     * @param type
     * @return
     */
    @RequestMapping(value = "check_valid.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> checkValid(String str, String type) {
        return iUserService.checkValid(str, type);
    }

    /**
     * 获取用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "get_user_info.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登录，无法获取当前用户的信息");
    }

    /**
     * 忘记密码
     *
     * @param username
     * @return
     */
    @RequestMapping(value = "forget_get_question.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetGetQuestion(String username) {
        return iUserService.selectQuestion(username);

    }

    @RequestMapping(value = "forget_check_answer.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetCheckAnswer(String username, String question, String answer) {
        return iUserService.checkAnswer(username, question, answer);
    }

    @RequestMapping(value = "forget_reset_password.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> forgetRestPassword(String username, String userpassword, String forgetToken) {
        return iUserService.forgetRestPassword(username, userpassword, forgetToken);
    }

    @RequestMapping(value = "rest_password.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> rsetPassword(HttpSession session, String passwordOld, String passwordNew) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        return iUserService.rsetPassword(passwordOld, passwordNew, user);
    }

    @RequestMapping(value = "update_information.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> update_information(HttpSession session, User user) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        //判断是否登录
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        user.setId(currentUser.getId());
        user.setUsername(currentUser.getUsername());
        ServerResponse<User> response = iUserService.updateInfomation(user);
        if (response.isSuccess()) {
            response.getData().setUsername(currentUser.getUsername());
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }
        return response;
    }

    @RequestMapping(value = "get_information.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> get_information(HttpSession session) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {

            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "未登录,需要强制登录status=10");
        }
        return iUserService.getInformation(currentUser.getId());
    }

}
